const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const multer = require('multer'); 

const getTable = require('./mongo').getTable;
const chat = getTable("chat");
const userCenter = getTable("userCenter");

// filter
const FILTER = {
  password: 0,
  __v: 0
}

const api = require('./api');

const app = express();

const server = require('http').Server(app);

const socket = require('socket.io')(server);
// session config
app.use(session({
  secret: Math.random() + "oasis",
  cookie: { maxAge: 60000 * 1000 },
  name: 'session_id'
}));

// cookie and body parser
app.use(cookieParser());
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

// interactor
app.use((req, res, next)=>{
  // return res.json({
  //   a:1
  // })
  next();
});

// test
app.get('/test', (req, res) => {
  req.session.name = 'ding.luchao';
  res.json({
      id: 1
  });
});

// test 403
app.get('/testauth', (req, res) => {
  res.status(403).json({
      id: 1
  });
});

app.get('/show', (req, res) => {
  res.json({
    name: req.session.name
  })
});

// api
app.use('/', api);

// socket
socket.on('connection', (ioSocket) => {
  // get client msg
  ioSocket.on('sendMsg', (msg) => {
    // 推送给所有客户端
    socket.emit('receive', msg);
    console.log(msg);
  });

  // 获取客户端聊天消息
  ioSocket.on('msg', (msg) => {
    msg = {...msg, create_time: new Date().getTime()};
    chat.create(msg, (err, doc) => {
      // 入库成功后消息广播
      socket.emit('receive', doc._doc);
    });
  });
});

server.listen(8777);
